package com.zhuxiang.dao.impl;

import com.zhuxiang.dao.UserDao;
import com.zhuxiang.entity.User;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
@Transactional
public class UserDaoImpl implements UserDao {
    @Autowired
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public void save(User user) {
        sessionFactory.getCurrentSession().save(user);
    }

    @Override
    public User selectByCellphone(String cellphone) {
        String hql = "from User where cellphone = ?";
        Query query = sessionFactory.getCurrentSession().createQuery(hql);
        query.setParameter(0,cellphone);
        return (User) query.uniqueResult();
    }

    @Override
    public User selectByEmail(String email) {
        String hql = "from User where email = ?";
        Query query = sessionFactory.getCurrentSession().createQuery(hql);
        query.setParameter(0,email);
        return (User) query.uniqueResult();
    }

    @Override
    public User selectByCellphoneOrEmailAndPwd(String cellphone, String email, String password) {
        String hql = "from User where ( cellphone = ? or email = ? ) and password = ?";
        Query query = sessionFactory.getCurrentSession().createQuery(hql);
        query.setParameter(0,cellphone);
        query.setParameter(1,email);
        query.setParameter(2,password);
        return (User) query.uniqueResult();
    }
}
